import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Trade.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fsuper/fsuper.dart';

class TradeInfoPage extends StatefulWidget {
  final String dirType;

  const TradeInfoPage({Key key, this.dirType}) : super(key: key);

  @override
  _TradeInfoPageState createState() => _TradeInfoPageState();
}

class _TradeInfoPageState extends State<TradeInfoPage> {
  EasyRefreshController controller = EasyRefreshController();
  ScrollController _scrollController;
  var _item = [];
  int pageNum = 0;

  @override
  void initState() {
    super.initState();
    debugPrint("交易类型：${widget.dirType}");
    _getTrade(true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).canvasColor,
      appBar: AppBar(
        backgroundColor: Theme.of(context).canvasColor,
        title: Text(
          null == widget.dirType ? "账户明细" : "收益明细",
          style: TextStyle(fontSize: 18),
        ),
        centerTitle: true,
      ),
      body: EasyRefresh.custom(
        enableControlFinishRefresh: true,
        header: CommWidget.commHeader(),
        footer: CommWidget.commFooter(),
        emptyWidget: _item.length == 0 ? CommWidget.nullWidget() : null,
        controller: controller,
        scrollController: _scrollController,
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return Column(
                  children: <Widget>[
                    _itemWidget(index),
                    Divider(height: 0, color: Color(0xffbbbbbb)),
                  ],
                );
              },
              childCount: _item.length,
            ),
          )
        ],
        onRefresh: () => _getTrade(true),
        onLoad: () => _getTrade(false),
      ),
    );
  }

  ///列表布局
  Widget _itemWidget(int index) {
    TradeEntity entity = _item[index];
    return Container(
      color: Theme.of(context).cardColor,
      padding: EdgeInsets.all(10.0),
      child: Column(
        children: <Widget>[
          _descWidget(entity),
          _timeWidget(entity),
        ],
      ),
    );
  }

  ///交易简介和金额
  Widget _descWidget(TradeEntity entity) {
    String money = "${entity.money}";
    Color moneyColor, descColor = Color(0xff333333);
    String desc = entity.tradeDesc ?? "结算";
    if (entity.dirType == '00') {
      money = "￥-$money";
      moneyColor = Colors.green;
    } else {
      moneyColor = Colors.red;
      money = "￥+$money";
    }
    if (entity.tradeType == "01") {
      desc = entity.status == "02"
          ? "处理中"
          : entity.status == "01" ? "提现失败" : "提现成功";
      switch (entity.status) {
        case "00":
          desc = "成功";
          break;
        case "01":
          desc = "失败";
          descColor = Colors.red;
          break;
        default:
          desc = "处理中";
          descColor = Colors.blueAccent;
          break;
      }
    }
    return Row(
      children: <Widget>[
        Text(
          desc,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: descColor,
          ),
        ),
        Expanded(flex: 1, child: Container()),
        Text(
          money,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: moneyColor,
          ),
        ),
      ],
    );
  }

  ///交易时间付款类型
  Widget _timeWidget(TradeEntity entity) {
    String type;
    if (entity.payType == '00') {
      type = "账户余额";
    } else if (entity.payType == "01") {
      type = "支付宝";
    } else {
      type = "微信";
    }
    if (entity.tradeType == "01") {
      type = '提现到$type';
    }
    if (entity.dirType == '01') {
      type = "赚钱收益";
    }
    return FSuper(
      width: double.infinity,
      text: type,
      textColor: Colors.grey,
      textSize: 12,
      textAlignment: Alignment.centerLeft,
      child1Alignment: Alignment.centerRight,
      child1: Text(
        entity.createAt,
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey,
        ),
      ),
    );
  }

  ///获取数据
  Future _getTrade(bool isRefresh) async {
    if (isRefresh) {
      pageNum = 0;
    }
    String url = '${Api.URL_TRADE_INFO}?pageNum=$pageNum';
    if (null != widget.dirType) {
      url += '&dirType=${widget.dirType}';
    }
    await Http.get(url, successCallBack: (data) {
      List list =
          json.decode(data).map((m) => TradeEntity.fromJson(m)).toList();
      setState(() {
        if (isRefresh) {
          _item.clear();
        }
        _item.addAll(list);
        pageNum++;
      });
      print("总数：${_item.length}");
      if (isRefresh) {
        controller.finishRefresh(success: true);
      } else {
        controller.finishLoad(
            success: true, noMore: null == list || list.length < 10);
      }
    }, errorCallBack: (error) {
      if (isRefresh) {
        controller.finishRefresh();
      } else {
        controller.finishLoad();
      }
    });
  }
}
